package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import dao.MyUserDao;
import pojo.MyUser;

@Repository
public class MyUserDaoImpl implements MyUserDao {

    @PersistenceContext(name="manager")
    private EntityManager manager;

    public int add(MyUser myUser) {
        manager.persist(myUser);
        return 1;
    }

    public MyUser get(String uname) {
        Query query = manager.createQuery("select u from MyUser u where u.uname=:name");
        query.setParameter("name",uname);
        MyUser myUser = (MyUser) query.getSingleResult();
        return myUser;
    }

    public int update(MyUser myUser) {
        MyUser user = (MyUser) manager.find(MyUser.class,myUser.getId());
        user.setUname(myUser.getUname());
        user.setPsd(myUser.getPsd());
        user.setAge(myUser.getAge());
        manager.flush();
        return 1;
    }

    public int delete(String id) {
        MyUser user = (MyUser) manager.find(MyUser.class,id);
        manager.remove(user);
        manager.close();
        return 1;
    }

    public List<MyUser> findAll() {
        Query query = manager.createQuery("from MyUser u");
        List<MyUser> myUsers =  query.getResultList();
        return myUsers;
    }


}
